package com.neusoft.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

public class OssUtil {
    public static String uploadFile(MultipartFile multipartFile) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        DefaultCredentialProvider credentialsProvider = CredentialsProviderFactory.newDefaultCredentialProvider("LTAI5tEEHoNMZ96c1Pg9xuP7","iAbAHbiNQV4UdLGc4rIUiWtHpXiI0n");
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "school-study-neusoft";
        // 获取原始文件名
        String objectName = multipartFile.getOriginalFilename();
        System.out.println("objectName:"+objectName);
        //截取文件类型
        String exName=objectName.substring(objectName.lastIndexOf("."));
        System.out.println("exName:"+exName);
        //根据时间生成文件夹
        LocalDate localDate = LocalDate.now();
        String format = localDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        System.out.println("format:"+format);
        //拼接存储路径
        String newName=format+"/"+ UUID.randomUUID()+exName;
        System.out.println("newName:"+newName);
        /*String filePath= "D:\\localpath\\examplefile.txt";*/

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            //获取文件输入流
            InputStream inputStream = multipartFile.getInputStream();
            // 创建PutObjectRequest对象。 传递桶名称  文件名  文件输入流
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, newName,inputStream);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {

            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        //将文件的映射地址拼接
        //
        https://school-study-neusoft.oss-cn-beijing.aliyuncs.com/2024/11/19/91e62e59-d76d-457b-bd4b-3b2fb919090e.png
        return "https://"+bucketName+"."+endpoint.split("://")[1]+"/"+newName;
    }

}
